import { defineStore } from 'pinia'
import { reactive, toRefs } from 'vue'
import { authApi } from '@/api/modules/auth/auth'
import { token as t } from '@/utils'
import type { LoginUser } from '@/typings'

export const useAuthStore = defineStore('auth', () => {
  const state = reactive({
    user: undefined as LoginUser | undefined
  })

  const getProfile = async () => {
    await authApi
      .profile()
      .then(resp => {
        if (resp.success) {
          state.user = resp.data
        }
      })
      .catch(() => {
        state.user = undefined
      })
  }

  const logout = async () => {
    if (state.user) {
      await authApi.logout().then(resp => {
        if (resp.success) {
          state.user = undefined
          t.remove()
          //todo context.dispatch('tag/delAllTags', null, { root: true })
        }
      })
    }
  }

  return { ...toRefs(state), getProfile, logout }
})
